<template>
  <div>
    <van-nav-bar title="注册" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
  <van-cell-group inset>
    <van-field
      v-model="tel"
      name="tel"
      label="手机号"
      placeholder="手机号"
      :rules="[{ validator: validatorTel }]"
    />
    <van-field
          v-model="sms"
          center
          clearable
          label="验证码"
          placeholder="验证码"
          :rules="[{ validator: validatorSMS }]"
        >
          <template #button>
            <van-button size="small" type="primary" plain @click="getCode">
              发送验证码
            </van-button>
          </template>
        </van-field>
    <van-field
      v-model="password"
      type="password"
      name="password"
      label="密码"
      placeholder="密码"
      :rules="[ { pattern: /[\w]{6,}/, required: true, message: '密码少6位' },]"
    />
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      注册
    </van-button>
  </div>
</van-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router"
import {checkTelAPI , msgCodeAPI,checkCodeAPI,userRegisterAPI} from "../../api/user"
import { showNotify } from "vant";
let $router =useRouter()
let tel = ref<string>("")
let sms = ref<string>("")
let password = ref<string>("");

// 手机号验证
const validatorTel = (val:string)=>{
  // 先判断手机号对不对
  if(!/^1[3-9]\d{9}$/.test(val)){
    return "手机号码哦格式错误"
  }
  // 调接口 检测手机号是否被注册
checkTelAPI({ tel: tel.value}).then((res)=>{
  if (res.data.code != 200) {
    // 如果已经被注册 弹出提示
      showNotify({ type: "danger", message: res.data.message });
    }
})
}

// 获取验证码
const getCode =()=>{
  msgCodeAPI({tel: tel.value}).then((res)=>{
    // console.log(res);
    if(res.data.code == 200){
      sms.value = res.data.data
    }
    
  })
}
// 验证码规则
const validatorSMS = (val: string) => {
  if (!/^\d{5}$/.test(val)) {
    return "请填写正确验证码";
  }
  // 调用接口 判断验证码是否正确
checkCodeAPI({}).then((res)=>{
  // 如果不正确 则不等于200 弹出提示框
  if(res.data.code !=200){
    showNotify({ type: "danger", message: res.data.message });
  }
})
}

// 点击注册按钮
const onSubmit = ()=>{
  // 调接口
  userRegisterAPI({tel:tel.value,password:password.value}).then((res)=>{
    // console.log(res);
    // 注册成功弹出提示框 再跳转到登录页面进行登录
    if(res.data.code == 200){
      showNotify({ type: "success", message: res.data.message });
      $router.push('/login')
    }
    
  })
}
// 点击<跳转到登录页面
const onClickLeft = ()=>{
  $router.push('/login')
}
</script>

<style scoped></style>
